package com.xxd.algo.newcode.base01.class02;

public class Code05_NetherlandsFlag {

    public static void partition2(int[] arr, int l, int r, int p) {
        int less = l;
        int more = r + 1;
        while (less < more) {
            if (arr[less] <= p) {
				less++;
            } else if (arr[less] > p) {
                swap(arr, --more, less);
            }
        }
    }

    public static int[] partition(int[] arr, int l, int r, int p) {
        int less = l - 1;
        int more = r + 1;
        while (l < more) {
            if (arr[l] < p) {
                swap(arr, ++less, l++);
            } else if (arr[l] > p) {
                swap(arr, --more, l);
            } else {
                l++;
            }
        }
        return new int[]{less + 1, more - 1};
    }

    // for test
    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    // for test
    public static int[] generateArray() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 3);
        }
        return arr;
    }

    // for test
    public static void printArray(int[] arr) {
        if (arr == null) {
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        //int[] test = generateArray();
        int[] test = {1, 3, 5, 1, 7, 2, 6, 3};

        printArray(test);
		partition2(test, 0, test.length - 1, 3);
        printArray(test);

        test = new int[]{1, 3, 5, 1, 7, 2, 6, 3};
        int[] res = partition(test, 0, test.length - 1, 3);

        printArray(test);
        System.out.println(res[0]);
        System.out.println(res[1]);

    }
}
